package com.imooc.socket;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class LengthCalculator extends Thread{

    private Socket socket;  // 以socket为成员变量

    public LengthCalculator(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {

            // 获取socket的输出流
            OutputStream os = socket.getOutputStream();
            // 获取socket的输入流
            InputStream is = socket.getInputStream();


            // 接受来自客户端的信息
            byte[] buff = new byte[1024];
            // buff主要用来读取输入的内容，存成byte数组，ch主要用来获取读取数组的长度
            int ch = is.read(buff);
            String content = new String(buff, 0, ch);
            System.out.println("----------------------");
            System.out.println("客户端：" + content);

            // 向客户端发送信息
            // 往输出流里写入获得的字符串的长度，回发给客户端
            Scanner input = new Scanner(System.in);
//            os.write(String.valueOf(content.length()).getBytes());
            System.out.print("您（服务器）：");
            String myInput = input.nextLine();
            os.write(myInput.getBytes());

            // 释放资源
            is.close();
            os.close();
            socket.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
